<template>
  <div class="app-container" id="areaDosage">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input v-model="keyWordName" placeholder="输入关键字进行过滤" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            v-loading="treeloading"
            show-checkbox
          />
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <!--大用户表历史数据-->
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch"
              :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                <el-form-item label="时间选择" prop="timevalue">
                  <el-date-picker
                    v-model="timevalue"
                    type="monthrange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM"
                    style="width: 100%;">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="楼栋名称" prop="ldName">
                  <el-input v-model="queryParams.ldName" placeholder="输入楼栋名称" clearable size="small"></el-input>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport"
            :hasPermiExport="['dataananysis:areadosage:export']"></RightDropdown>
        </el-row>
        <el-row>
          <el-table v-loading="loading" :data="dataList" max-height="600" ref="table">
            <el-table-column v-for="item in columns"  :key="item.key" :prop="item.dataIndex" align="center" :show-overflow-tooltip="true" :label="item.label" v-if="item.visible"/>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getDosageList } from "@/api/datastatistics/meterread/areadosage.js"
import moment from 'moment'

export default {
  name: "AreaDosage",
  data() {
    return {
      // 列信息
      columns: [
        { key: 0, label: `楼栋名称`, visible: true, dataIndex:'ldName' },
        { key: 1, label: `开始月份`, visible: true, dataIndex:'beginTime' },
        { key: 2, label: `结束月份`, visible: true, dataIndex:'endTime' },
        { key: 3, label: `户数`, visible: true, dataIndex:'familyNum' },
        { key: 4, label: `用量(m³)`, visible: true, dataIndex:'dosage' },
      ],
      size: 'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '80px',
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表格数据
      dataList: [],
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      treeloading: true,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        areaCode: [],
        beginTime: null,
        endTime: null,
        ldName: null,
      },
      // 总条数
      total: 0,
      showtime: true,
      // 冻结日期
      timevalue: [moment(new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDate())).format('YYYY-MM'), moment(new Date()).format('YYYY-MM')],
    };
  },
  // created() {
  //   this.tip()
  //   this.getAreaTree()
  // },
  mounted() {
    this.tip()
    this.getAreaTree()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    timevalue(val){
    }
  },
  methods: {
    // 初始化表格 解决表格固定操作列的问题
    init(){
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.table.doLayout()
        }, 100)
      })
    },
    // 重置表单
    resetQuery() {
      this.dataList = []
      this.$refs.tree.setCheckedNodes([]);
      this.timevalue = [moment(new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDate())).format('YYYY-MM'), moment(new Date()).format('YYYY-MM')],
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        areaCode: [],
        beginTime: moment(new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDate())).format('YYYY-MM'),
        endTime: moment(new Date()).format('YYYY-MM'),
        ldName: null,
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let choiseCheckList = this.$refs.tree.getCheckedNodes();
      let newchoiseCheckList= []

      if (choiseCheckList.length > 0) {
        choiseCheckList.forEach((item) => {
        newchoiseCheckList.push(item.areaCode)
      })
        this.queryParams.areaCode = newchoiseCheckList
        if(this.timevalue == null){
          this.$modal.msgWarning("请选择时间!")
        }else if(this.timevalue.length == 2){
          this.queryParams.beginTime = this.timevalue[0]
          this.queryParams.endTime = this.timevalue[1]
          this.getList()
        }
      } else if (choiseCheckList.length === 0) {
        this.$modal.msgWarning("至少选择一个区域!")
      }
    },
    // 获取表格数据
    getList() {
      this.loading = true;
      getDosageList(this.queryParams).then(response => {
        if(response.code === 200){
          this.dataList = response.rows
          this.init()
          this.loading = false;
          this.total = response.total
        }else{
          this.$modal.msgError("数据查看失败!")
          this.loading = false;
        }
      });
    },
    // 页面提示信息
    tip(){
      this.$modal.msgWarning("请选择一个区域查看数据!")
      this.loading = false;
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      this.treeloading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        var obj = {
          id: item.areaCode,
          label: item.areaName,
          areaCode: item.areaCode,
          children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
        }
        this.areaOptions.push(obj)
      })
      this.treeloading = false
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow() {
      this.treeVisibale = !this.treeVisibale
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalXbStatisticAnalysis/exportAreaDosage', {
        ...this.queryParams
      }, `区域月用量_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 30%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
  </style>
